# encoding=utf-8
"""
响应对象业务校验
"""
import logging

from scrapy.exceptions import IgnoreRequest, DropItem
from scrapy.utils.project import get_project_settings
from zc_core.middlewares.proxies.proxy_facade import ProxyFacade
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request
from suzhou.utils.cookie_builder import build_cookie
from pyquery import PyQuery

logger = logging.getLogger(__name__)


class BizValidator(BaseValidateMiddleware):

    def __init__(self):
        super(BizValidator, self).__init__()
        settings = get_project_settings()
        self.proxy_facade = ProxyFacade(settings)

    def validate_item(self, request, response, spider):
        proxy = request.meta['proxy']
        if '该ip已被封禁' in response.text and proxy:
            proxy = proxy.replace('http://', '').replace('https://', '')
            self.proxy_facade.pool.remove_proxy(proxy)
            logger.info('反爬1: [%s]' % proxy)
            return retry_request(request)
        if '正在进入页面，请稍后' in response.text and proxy:
            # proxy = proxy.replace('http://', '').replace('https://', '')
            # self.proxy_facade.pool.remove_proxy(proxy)
            logger.info('反爬2: [%s]' % proxy)
            return retry_request(request)
        if 'Auth Failed' in response.text and proxy:
            proxy = proxy.replace('http://', '').replace('https://', '')
            self.proxy_facade.pool.remove_proxy(proxy)
            logger.info('反爬3: [%s]' % proxy)
            return retry_request(request)
        if response.status == 404:
            raise IgnoreRequest('资源找不到: [%s]' % request.meta.get('skuId'))
        jpy = PyQuery(response.text)
        result = jpy('.goods_price:contains("此商品已下架，欢迎选购其他商品。")')
        if result:
            sku_id = request.meta.get('skuId')
            raise IgnoreRequest('[Item]下架：[%s]' % sku_id)
        return response

    def validate_cert(self, request, response, spider):
        if not response.text:
            meta = response.meta
            sku_id = meta.get('skuId')
            logger.info('无资质: [%s]' % sku_id)
            raise IgnoreRequest(f"无资质 [{sku_id}]")

        return response
